/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        vector<pair<TreeNode*, unsigned int>> q; // ⽤数组模拟队列，结点+下标
        q.push_back({root, 0}); // 数组右边进，左边出
        unsigned int ret = 0;
        while(!q.empty())
        {
            // 先更新这⼀层的宽度
            auto& [x1, y1] = q[0];
            auto& [x2, y2] = q.back();
            ret = max(ret, y2 - y1 + 1);
 
            vector<pair<TreeNode*, unsigned int>> tmp; // 下层非空结点入队，直接替换即可
            for(auto& [x, y] : q) // 获取 结点+下标
            {
                if(x->left != nullptr)
                    tmp.push_back({x->left, y * 2 + 1});
                if(x->right != nullptr)
                    tmp.push_back({x->right, y * 2 + 2});
            }
            q = tmp;
        }
        return ret;
    }
};